import React, { useState } from 'react';
import { Form, Input, Modal, Radio, Select,Upload,message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
// import SelectDeviceModal from './selectDeviceModal';
const { Option } = Select;

const FormItem = Form.Item;

export interface UpdateFormProps {
  onCancel: () => void;
  onSubmit: (values: API.SysDeviceAttrItem) => void;
  updateModalVisible: boolean;
  values:  API.SysDeviceAttrItem;
  devicetype:API.DictItem[];
}

const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const [formVals, setFormVals] = useState<API.SysDeviceAttrItem>(props.values);
  const [attrType,setAttrType] = useState<string>('common');
  const [selectDeviceModalVisible, handleDeviceModalVisible] = useState<boolean>(false);
  const [selectedKeys,setSelectedKeys] = useState<string>();
  const [selectedNames,setSelectedNames] = useState<string>();
  const [deviceType,setDeviceType] = useState<number>(props?.values?.deviceTypeId);
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();

  const { updateModalVisible, onSubmit: handleUpdate,  onCancel,devicetype} = props;

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    fieldsValue.attrId = formVals.attrId;
    fieldsValue.attrImg=formVals.attrImg;
  
    form.resetFields();
    handleUpdate(fieldsValue);
  };


  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">上传图标</div>
    </div>
  );

  const handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    console.log(info.file);
    if (info.file.status === 'done') {
      
      const pic = info.file.response
      setFormVals({ ...formVals, ...{ attrImg: pic.attachCode } });
      setLoading(false);
    }
  };

  const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传JPG/PNG文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图像必须小于2MB!');
    }
    return isJpgOrPng && isLt2M;
  }
  
  const validatorValue = async (_: any, value: string) => {
    const promise = Promise;
    console.log(value)
    if(Number(value)>999999999999){
      return promise.reject("值不能超过99999999999");
    }

    if(_.field=='maxValue'&&Number(value)<Number(form.getFieldValue('minValue'))){
      return promise.reject("最大值不能小于最小值");
    }
    return promise.resolve();
  };

  const getOption = (list: API.DictItem[]) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.typeId} value={item.typeId}>
        {item.typeName}
      </Option>
    ))
  }
  return (
    <Modal
      width={640}
     
      destroyOnClose
      title="编辑设备变量"
      visible={updateModalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
       <Form
        {...formLayout}
        form={form}
        initialValues={{
          deviceTypeId: formVals.deviceTypeId,
          orderNo: formVals.orderNo,
          attrType: formVals.attrType,
          dispalyName: formVals.dispalyName,
          browseName: formVals.browseName,
          unit: formVals.unit,
          dataType: formVals.dataType,
          minValue: formVals.minValue,
          maxValue: formVals.maxValue,
          useState: formVals.useState,
          devices:selectedNames
        }}
      >
          <FormItem
          label="变量类别"
          name="attrType"
          
        >
          <Radio.Group   onChange={(e)=>{setAttrType(e.target.value)}} >
            <Radio value={'common'} >
              公共变量
            </Radio>
            <Radio value={'special'}>
              特有变量
            </Radio>
          </Radio.Group>
        </FormItem>
             {/* setDeviceType */}
             <FormItem
        // style={{display:attrType=='special'?'flex':'none'}}
            label="设备类型"
            name="deviceTypeId"
          //  rules={[{ required:(attrType=='special'?true:false), message: '请选择设备类型' }]}
            rules={[{ required:true, message: '请选择设备类型' }]}
          >
            <Select placeholder="请选择"   onChange={(e)=>{setDeviceType(e)}}> 
            {getOption(devicetype)} 
            </Select>
          </FormItem>
          {/* <FormItem
            style={{display:attrType=='special'?'flex':'none'}}
            label="设备"
             rules={[{ required:(attrType=='special'?true:false), message: '请选择设备' }]}
        >
          <Input placeholder="请选择设备" value={selectedNames}   onClick={() => handleDeviceModalVisible(true)}  />
        </FormItem> */}
        {/* <FormItem
          label="序号"
          name="orderNo"
          rules={[{ required: true },{ validator: validatorValue}]}
        >
        
          <Input type="number" placeholder="请输入"   /> 
        </FormItem> */}
      
        <FormItem
          label="变量名称"
          name="dispalyName"
          rules={[{ required: true,  min: 2 ,  max: 64}]}
        >
          <Input placeholder="请输入" autoComplete='off' />
        </FormItem>
        <FormItem
          label="页面展示名称"
          name="browseName"
          rules={[{ required: true,  min: 2 ,  max: 64 }]}
        >
          <Input placeholder="请输入" autoComplete='off' />
        </FormItem>
        <FormItem
          label="图标"
          name="attrImg"
        >
        <Upload
                name="file"
                listType="picture-card"
                showUploadList={false}
                // className={styles.uploader}
               // headers={{ 'x-auth-token': getToken() }}
                action="/api/imageUpload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {formVals.attrImg ? <img src={'/img/'  + formVals.attrImg} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
              </Upload>

        </FormItem>
        <FormItem
          label="单位"
          name="unit"
          rules={[{  max: 16}]}
        >
          <Input placeholder="请输入" autoComplete='off' />
        </FormItem>
        <FormItem
          label="数据类型"
          name="dataType"
          rules={[{ required: true}]}
        >
          <Select placeholder="请选择">
            <Option key={1} value={'int'}>整数</Option>
            <Option key={1} value={'decimal'}>小数</Option>
            <Option key={2} value={'varchar'}>字符串</Option>
            <Option key={3} value={'datatime'}>时间</Option>
            <Option key={4} value={'data'}>日期</Option>
          </Select>
        </FormItem>

     
        <FormItem
          label="最小值"
          name="minValue"
          rules={[ { validator: validatorValue}]}
        
        >
         <Input type="number" placeholder="请输入"   />
        </FormItem>
        <FormItem
          label="最大值"
          name="maxValue"
          rules={[ { validator: validatorValue}]}
        
        ><Input type="number" placeholder="请输入"   />
       
        </FormItem>
        <FormItem
          label="启用状态"
          name="useState"
        >
          <Radio.Group>
            <Radio value={1} >
              启用
            </Radio>
            <Radio value={0}>
              禁用
            </Radio>
          </Radio.Group>
        </FormItem>
      </Form>
      {/* <SelectDeviceModal
        onSubmit={async (ids,names) => {
          setSelectedKeys(ids);
          setSelectedNames(names);
          handleDeviceModalVisible(false);
          }}
        onCancel={() => handleDeviceModalVisible(false)}
        modalVisible={selectDeviceModalVisible}
        deviceType={deviceType}
      
      /> */}
    </Modal>
  );
};

export default UpdateForm;
